package com.bigtree.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.bigtree.controller.conf.R;
import com.bigtree.domain.Book;
import com.bigtree.service.BookService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/books")
public class BookController {
    @Autowired
    BookService bookService;
    //cheng增
    @PostMapping()
    public  R insert(@RequestBody Book book){
        return new R(bookService.save(book));
    }

    //cheng删 传进来一个id，进行删除操作，然后将删除结果用r封装格式，json格式返回前端
    @DeleteMapping("/{id}")
    public R delete(@PathVariable Integer id){
        return new R(bookService.removeById(id));
    }


    //cheng改
    @PutMapping
    public R update(@RequestBody Book book){
        return new R(bookService.updateById(book));
    }


    //cheng查所有
    @GetMapping
    public R getAll(){
        return new R(bookService.list());
    }

    // 分页查询
    @GetMapping("{currentPage}/{pageSize}")
    public R getPage(@PathVariable int currentPage,@PathVariable int pageSize){
        IPage<Book> page = bookService.getPage(currentPage,pageSize);
        if(currentPage>page.getPages()){
            page=bookService.getPage((int)page.getPages(),pageSize);
        }

        return new R(true,page);
    }


//*
//*分页查询和模糊查询不能同时存在*/

    //模糊查询，交给分页查询
   // @GetMapping({current}/{size})
    @GetMapping("{current}/{size}")
    public R getPageLike(@PathVariable int current,@PathVariable int size,Book book){

        return new R(bookService.getPageLike(current,size,book));

    }



    //cheng 根据id查数据
    @GetMapping("/{id}")
    public R getById(@PathVariable int id){
        R r = new R();
        r.setFlag(true);
        r.setData(bookService.getById(id));
        return r;
    }


}
